package com.itheima.intercetor;

import com.alibaba.fastjson.JSON;
import com.itheima.common.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author liudo
 * @version 1.0
 * @project tlias-backend
 * @date 2023/9/12 16:04:31
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        // 1. 获取令牌，看看有没有？ -- 令牌在哪？ 请求头
        String token = httpServletRequest.getHeader("Token");
        if (!StringUtils.hasText(token)) {
            // 不放行，但是要返回固定的结果 { "code": 0, "msg": "NOT_LOGIN", "data": null }
            Result<Object> result = new Result<>();
            result.setCode(0);
            result.setMsg("NOT_LOGIN");
            // 把对象转成json
            String jsonString = JSON.toJSONString(result);
            // 把json写进响应体
            httpServletResponse.getWriter().write(jsonString);
            return false;
        }
        // 2. 看看令牌非法不非法
        try {
            Claims body = Jwts.parser()
                    .setSigningKey("itheima")
                    .parseClaimsJws(token)
                    .getBody();
            return true;
        } catch (Exception e) {
            // 3. 如果不放行，我该如何通知前端进行登录呢? -- 不是随便报错 -- 接口文档
            Result<Object> result = new Result<>();
            result.setCode(0);
            result.setMsg("NOT_LOGIN");
            // TODO 手动给它变JSON 放进响应体中 这里需要序列化工具
            String jsonString = JSON.toJSONString(result);
            httpServletResponse.getWriter().write(jsonString);
            return false;
        }
    }
}
